import axios from 'axios'
import type { AxiosInstance } from 'axios'
import type { XMRequestInterceptors, XMRequestConfig } from './type'
import { ElLoading } from 'element-plus/lib/index'
import { LoadingInstance } from 'element-plus/lib/components/loading/src/loading'
const defaultloading = false

class XMRequest {
  instance: AxiosInstance
  interceptors?: XMRequestInterceptors
  showLoading: boolean
  loading?: LoadingInstance
  //   传入不同配置的时候每次都会创建一个新的实例对象
  constructor(config: XMRequestConfig<any>) {
    this.instance = axios.create(config)
    this.interceptors = config.interceptors
    this.showLoading = config.showLoading ?? defaultloading
    // 2. 从config中取出的拦截器是对应的实例的拦截器
    this.instance.interceptors.request.use(
      this.interceptors?.requestInterceptor,
      this.interceptors?.requestInterceptorCatch
    )
    this.instance.interceptors.response.use(
      this.interceptors?.responseInterceptor,
      this.interceptors?.responseInterceptorCatch
    )
    // 所有实例都有的拦截器
    this.instance.interceptors.request.use(
      (config) => {
        if (this.showLoading) {
          this.loading = ElLoading.service({
            lock: true,
            text: '正在请求数据...',
            background: 'rgba(0,0,0,.5)'
          })
        }

        return config
      },
      (err) => {
        console.log('请求失败')
        return err
      }
    )
    this.instance.interceptors.response.use(
      (res) => {
        setTimeout(() => {
          this.loading?.close()
        }, 3000)
        const data = res.data
        if (data.returnCode == '-1001') {
          console.log('请求失败')
        } else {
          return data
        }
      },
      (err) => {
        this.loading?.close()
        if (err.response.status === 404) {
          console.log('请求404')
        }
      }
    )
  }

  request<T = any>(config: XMRequestConfig): Promise<T> {
    return new Promise((resolve) => {
      if (config.interceptors?.requestInterceptor) {
        config = config.interceptors.requestInterceptor(config)
      }
      if (config.showLoading === defaultloading) {
        this.showLoading = config.showLoading
      }

      this.instance.request<any, T>(config).then((res) => {
        // 单个请求对数据处理
        if (config.interceptors?.responseInterceptor) {
          // res = config.interceptors.responseInterceptor(res)
        }
        this.showLoading = true

        resolve(res)
      })
    })
  }
  get<T = any>(config: XMRequestConfig): Promise<T> {
    return this.request<T>({ ...config, method: 'GET' })
  }
  post<T = any>(config: XMRequestConfig): Promise<T> {
    return this.request<T>({ ...config, method: 'POST' })
  }
}
export default XMRequest
